package com.example.administrator.foodrowfresh.jiao;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.administrator.foodrowfresh.R;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class FindPassActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText tellEditText, passEditText, pass, messageEditText;
    private Button getCord, saveCord;
    //倒计时

    private String iPhone;

    private int time = 60;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == -9) {
                getCord.setText("重新发送(" + time + ")");
            } else if (msg.what == -8) {
                getCord.setText("获取验证码");
                getCord.setClickable(true);
                time = 30;
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("event", "event=" + event);
                if (result == SMSSDK.RESULT_COMPLETE) {
                    // 短信注册成功后,然后提示
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
                        Toast.makeText(getApplicationContext(), "提交验证码成功",
                                Toast.LENGTH_SHORT).show();

                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Toast.makeText(getApplicationContext(), "正在获取验证码",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(FindPassActivity.this, "验证失败", Toast.LENGTH_SHORT).show();
                        ((Throwable) data).printStackTrace();
                    }
                }
            }
        }


    };
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_pass);
        initView();
        setListener();
    }

    private void setListener() {
        getCord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iPhone = tellEditText.getText().toString();
                if (isInputCorrect(iPhone) == true) {
                    SMSSDK.getVerificationCode("86", iPhone);
                    getCord.setClickable(false);
                    getCord.setText("重新发送" + time);

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (; time > 0; time--) {
                                handler.sendEmptyMessage(-9);
                                if (time < 0) {
                                    break;
                                }
                                try {
                                    Thread.sleep(1 * 1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            handler.sendEmptyMessage(-8);
                        }
                    }).start();
                }

            }
        });
    }

    //判断输入是否合理
    private boolean isInputCorrect(String phone) {
        if (TextUtils.isEmpty(phone)) {
            //设置抖动效果

//            tellEditText.setShakeAnimation();
            //设置吐司提示
            Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        //手机注册
        if (regexTel(phone) == false) {
            //设置抖动效果
//            tellEditText.setShakeAnimation();
            Toast.makeText(FindPassActivity.this, "手机号输入不正确", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    //判断手机号输入是否正确的正则表达式
    public static boolean regexTel(String tel) {
        Pattern pattern = Pattern.compile("^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$");
        Matcher matcher = pattern.matcher(tel);
        return matcher.matches();
    }

    private void initView() {
//        now = (TextView) findViewById(R.id.now);

        pass = (EditText) findViewById(R.id.shopping_tv_tell_new_pass);
        messageEditText = (EditText) findViewById(R.id.shopping_tv_find_verification_code);
        tellEditText = (EditText) findViewById(R.id.shopping_tv_tell);
        passEditText = (EditText) findViewById(R.id.shopping_tv_tell_pass);
        getCord = (Button) findViewById(R.id.shopping_bt_find_pass_gain_message);
        saveCord = (Button) findViewById(R.id.shopping_bt_find_pass_sureModify);


        getCord.setOnClickListener(this);
        saveCord.setOnClickListener(this);


        initSMS();
    }

    public void onClick(View view) {
        if (view != null) {
            switch (view.getId()) {

                case R.id.find_tool_back_n:
                    finish();
                    break;
                //获取验证码
                case R.id.shopping_bt_find_pass_gain_message:
                    iPhone = tellEditText.getText().toString();
                    if (TextUtils.isEmpty(iPhone)) {
                        //设置抖动效果
//                        tellEditText.setShakeAnimation();
                        //设置吐司提示
                        Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (isInputCorrect(iPhone) == false) {
                        return;
                    } else {
                        SMSSDK.getVerificationCode("86", iPhone);
                    }
                    break;
                //确认修改
                case R.id.shopping_bt_find_pass_sureModify:
                    if (tellEditText != null && passEditText != null && pass != null && messageEditText != null) {
                        iPhone = tellEditText.getText().toString();
                        String passStr = pass.getText().toString();
                        String passSureStr = passEditText.getText().toString();

                        //判断手机是否注册过
                        //判断两次密码输入是否一致
                        // 验证验证码
                        sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);

                        if (passStr.equals(passSureStr)) {
                            //SharedPreferences读数据
                            // 读取已保存的数据
                            String content = sharedPreferences.getString("content", "default value");


                            if (iPhone.equals(content)) {
                                // 第一步，获取SharedPreferences编辑者对象
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                // 第二步，使用编辑者对象对数据进行存储操作（编辑数据）
                                String tell = tellEditText.getText().toString();
                                String pass = passEditText.getText().toString();
                                editor.putString("content", content);
                                editor.putString("pass", pass);

                                // 第三步，提交编辑内容
                                editor.commit();


                                //核对验证码
                                SMSSDK.submitVerificationCode("86", iPhone, messageEditText.getText().toString().trim());
                            } else {
                                Toast.makeText(FindPassActivity.this, "亲！还没注册，是不能直接修改密码的=_=", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                    finish();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 短信初始化
     */
    private void initSMS() {
        SMSSDK.initSDK(this, "1282eba8d880f", "100b0f0b98507a77f9762d9021ae399b");
        EventHandler eh = new EventHandler() {

            @Override
            public void afterEvent(int event, int result, Object data) {

                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);

            }
        };
        SMSSDK.registerEventHandler(eh); //注册短信回调
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }


}
